import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiTrainingDatasetMetaApi } from '#/api/ai/dataset/trainingDatasetMeta';
import type { DescriptionItemSchema } from '#/components/description';

import { h } from 'vue';

import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { handleTree } from '@vben/utils';

import { Rate, Typography } from 'ant-design-vue';

import { getTrainingDatasetCategoriesList } from '#/api/ai/dataset/trainingDatasetCategories';
import { getTrainingDatasetTagPage } from '#/api/ai/dataset/trainingDatasetTag';
import { getVersionNumList } from '#/api/ai/dataset/trainingDatasetVersions';
import { getDeptListCondition } from '#/api/system/dept';
import { DictBadge } from '#/components/dict-badge';
import DictTag from '#/components/dict-tag/dict-tag.vue';
import { getRangePickerDefaultProps } from '#/utils';

const { Paragraph } = Typography;
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'datasetName',
      label: '数据集名称',
      rules: 'required',
      component: 'Input',
      componentProps: {
        placeholder: '请输入数据集名称',
      },
    },
    {
      fieldName: 'categoryId',
      label: '场景分类',
      component: 'ApiTreeSelect',
      componentProps: {
        allowClear: true,
        api: async () => {
          const data = await getTrainingDatasetCategoriesList({});
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择场景分类',
        treeDefaultExpandAll: true,
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'status',
      label: '状态',
      rules: 'selectRequired',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.AI_DATASET_STATUS),
        placeholder: '请选择状态',
      },
    },
    {
      fieldName: 'isPublic',
      label: '是否公开',
      component: 'RadioGroup',
      defaultValue: false,
      rules: 'required',
      componentProps: {
        options: [
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ],
        buttonStyle: 'solid',
        optionType: 'button',
      },
    },
    {
      fieldName: 'versionNum',
      label: '版本号',
      component: 'Input',
      rules: 'required',
      componentProps: {
        placeholder: '请输入版本号',
      },
    },
    {
      fieldName: 'source',
      label: '数据来源',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.AI_DATASET_SOURCE),
        placeholder: '请选择数据来源，如：manual/auto/imported',
      },
    },
    {
      fieldName: 'sort',
      label: '排序',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请输入排序',
      },
    },
    {
      fieldName: 'language',
      label: '语言',
      component: 'Select',
      defaultValue: 'zh_CN',
      componentProps: {
        options: getDictOptions(DICT_TYPE.AI_LANGUAGE),
        placeholder: '请选择语言',
      },
    },
    {
      fieldName: 'taskType',
      label: '阶段类型',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.AI_DATASET_TASK_TYPE),
        placeholder: '请选择阶段类型',
      },
    },
    {
      fieldName: 'dataFormat',
      label: '数据格式',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.AI_DATASET_DATA_FORMAT),
        placeholder: '请选择数据格式',
      },
    },
    {
      fieldName: 'outJsonPath',
      label: '输出路径',
      component: 'Input',
      componentProps: {
        placeholder: '请输入json文件输出路径',
      },
    },
    {
      fieldName: 'areaCode',
      label: '行政区划',
      component: 'ApiTreeSelect',
      componentProps: {
        api: async () => {
          const data = await getDeptListCondition({ type: 'area' });
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择行政区划',
        treeDefaultExpandAll: true,
        allowClear: true,
      },
    },
    {
      fieldName: 'orgId',
      label: '所属组织',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['areaCode'],
        async componentProps(value) {
          return {
            key: value.areaCode || 'all',
            // 异步获取组织树数据
            api: async () => {
              const data = await getDeptListCondition({
                areaCode: value.areaCode,
              }); // 调用接口获取部门/组织数据
              const treeData = handleTree(data); // 转换成树形结构

              const currentOrgId = value.deptId; // 获取当前用户所属的组织ID（

              // 递归遍历树，禁用当前用户的组织节点
              const disableCurrentOrg = (nodes) => {
                return nodes.map((node) => {
                  // 如果节点ID是当前组织ID，则禁用该节点
                  if (node.id === currentOrgId) {
                    node.disabled = true;
                  }
                  // 如果有子节点，递归处理
                  if (node.children && node.children.length > 0) {
                    node.children = disableCurrentOrg(node.children);
                  }
                  return node;
                });
              };

              return disableCurrentOrg(treeData); // 返回处理后的树数据
            },
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            multiple: false,
            placeholder: '请选择组织',
            defaultValue: value.deptId ? [value.deptId] : [], // 默认选中当前组织（如果有值）
          };
        },
        trigger(values, formApi) {
          // 清空值，避免残留
          formApi.setFieldValue('orgId', undefined);
        },
      },
    },
    {
      fieldName: 'qualityScore',
      label: '质量评分',
      component: 'Rate',
      componentProps: {
        allowHalf: true,
        count: 5,
        allowClear: true,
      },
    },
    {
      fieldName: 'jsonTemplate',
      label: '训练模版',
      component: 'Textarea',
      formItemClass: 'col-span-2',
      componentProps: {
        rows: 4,
        placeholder: '请输入训练文件生成JSON模版',
      },
    },
    {
      fieldName: 'description',
      label: '数据集介绍',
      component: 'RichTextarea',
      formItemClass: 'col-span-2',
    },
    {
      fieldName: 'tagNameList',
      label: '标签',
      component: 'ApiPagingSelect',
      formItemClass: 'col-span-2',
      componentProps: {
        allowClear: true,
        api: getTrainingDatasetTagPage,
        labelField: 'name',
        valueField: 'name',
        placeholder: '请选择标签',
        mode: 'tags',
      },
    },
  ];
}

/** 详情页字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
  return [
    {
      label: '数据集名称',
      field: 'datasetName',
    },
    {
      label: '场景分类',
      field: 'categoryName',
    },
    {
      label: '数据来源',
      field: 'sourceName',
    },
    {
      label: '数据总数',
      field: 'totalSamples',
    },

    {
      label: '版本号',
      field: 'versionNum',
    },
    {
      label: '状态',
      field: 'status',
      render: (val) =>
        h(DictTag, {
          type: DICT_TYPE.AI_DATASET_STATUS,
          value: val,
        }),
    },
    {
      label: '排序',
      field: 'sort',
    },
    {
      label: '语言',
      field: 'language',
      render: (val) =>
        h(DictTag, {
          type: DICT_TYPE.AI_LANGUAGE,
          value: val,
        }),
    },
    {
      label: '阶段类型',
      field: 'taskType',
      render: (val) =>
        h(DictTag, {
          type: DICT_TYPE.AI_DATASET_TASK_TYPE,
          value: val,
        }),
    },
    {
      label: '数据格式',
      field: 'dataFormat',
      render: (val) =>
        h(DictTag, {
          type: DICT_TYPE.AI_DATASET_DATA_FORMAT,
          value: val,
        }),
    },
    {
      label: '存放路径',
      field: 'filePath',
    },
    {
      label: '输出路径',
      field: 'outJsonPath',
    },
    {
      label: '行政区划',
      field: 'areaName',
    },
    {
      label: '所属组织',
      field: 'orgName',
    },
    {
      label: '质量评分',
      field: 'qualityScore',
      render: (val) => h(Rate, { value: val, disabled: true }),
    },
    {
      label: '是否公开',
      field: 'isPublic',
      render: (val) =>
        h(DictBadge, {
          value: val,
        }),
    },
    {
      field: 'jsonTemplate',
      label: '训练模版',
      span: 2,
      render: (val) =>
        h('div', {
          innerHTML: val,
          class: 'whitespace-pre-wrap text-sm leading-relaxed',
        }),
    },
    {
      label: '数据集介绍',
      field: 'description',
      span: 2,
      render: (val) => h('div', { innerHTML: val }),
    },
    {
      label: '标签',
      field: 'tagNameList',
      span: 2,
      render: (val) =>
        h(DictTag, {
          value: val,
        }),
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'datasetName',
      label: '数据集名称',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入数据集名称',
      },
    },
    {
      fieldName: 'categoryId',
      label: '场景分类',
      component: 'ApiTreeSelect',
      componentProps: {
        allowClear: true,
        api: async () => {
          const data = await getTrainingDatasetCategoriesList({});
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择上级数据集分类',
        treeDefaultExpandAll: true,
      },
    },
    {
      fieldName: 'source',
      label: '数据来源',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.AI_DATASET_SOURCE),
        placeholder: '请选择数据来源，如：manual/auto/imported',
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.AI_DATASET_STATUS),
        placeholder: '请选择状态',
      },
    },
    {
      fieldName: 'createTime',
      label: '创建时间',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
    {
      fieldName: 'language',
      label: '语言',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.AI_LANGUAGE),
        placeholder: '请选择语言',
      },
    },
    {
      fieldName: 'taskType',
      label: '阶段类型',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.AI_DATASET_TASK_TYPE),
        placeholder: '请选择阶段类型',
      },
    },
    {
      fieldName: 'dataFormat',
      label: '数据格式',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.AI_DATASET_DATA_FORMAT),
        placeholder: '请选择数据格式',
      },
    },
    {
      fieldName: 'areaCode',
      label: '行政区划编码',
      component: 'ApiTreeSelect',
      componentProps: {
        api: async () => {
          const data = await getDeptListCondition({ type: 'area' });
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择行政区划',
        treeDefaultExpandAll: true,
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<AiTrainingDatasetMetaApi.TrainingDatasetMeta>['columns'] {
  return [
    { type: 'checkbox', width: 40 },
    {
      field: 'id',
      title: '数据集主表id',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'datasetName',
      title: '数据集名称',
      minWidth: 120,
    },
    {
      field: 'categoryName',
      title: '场景分类',
      minWidth: 120,
    },
    {
      field: 'source',
      title: '数据来源',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.AI_DATASET_SOURCE },
      },
    },
    {
      field: 'totalSamples',
      title: '数据总数',
      minWidth: 120,
    },
    {
      field: 'versionNum',
      title: '版本号',
      minWidth: 120,
    },
    {
      field: 'status',
      title: '状态',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.AI_DATASET_STATUS },
      },
    },
    {
      field: 'sort',
      title: '排序',
      minWidth: 120,
    },
    {
      field: 'createTime',
      title: '创建时间',
      minWidth: 120,
      formatter: 'formatDateTime',
    },
    {
      field: 'language',
      title: '语言',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.AI_LANGUAGE },
      },
    },
    {
      field: 'taskType',
      title: '阶段类型',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.AI_DATASET_TASK_TYPE },
      },
    },
    {
      field: 'dataFormat',
      title: '数据格式',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.AI_DATASET_DATA_FORMAT },
      },
    },
    {
      field: 'filePath',
      title: '源文件存放路径',
      minWidth: 120,
    },

    {
      field: 'outJsonPath',
      title: 'json文件输出路径',
      minWidth: 120,
    },
    {
      field: 'areaName',
      title: '行政区划',
      minWidth: 120,
    },
    {
      field: 'orgName',
      title: '所属组织',
      minWidth: 120,
    },
    {
      field: 'qualityScore',
      title: '质量评分',
      minWidth: 120,
    },
    {
      field: 'isPublic',
      title: '是否公开',
      minWidth: 120,
      cellRender: {
        name: 'CellDictBadge',
      },
    },
    {
      field: 'actions',
      title: '操作',
      width: 260,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 用户导入的表单 */
export function useImportFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      label: '数据集Id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'versionId',
      label: '版本Id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'dataFormat',
      label: '数据格式',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.AI_DATASET_DATA_FORMAT),
        placeholder: '请选择数据格式',
      },
      defaultValue: 'alpaca',
      rules: 'required',
    },
    {
      fieldName: 'versionNum',
      label: '版本号',
      component: 'AutoComplete',
      dependencies: {
        if: (values) => values.id,
        triggerFields: ['id'],
        async componentProps(values) {
          const list = await getVersionNumList(values.id);
          const options = list.map((item) => ({
            value: item.versionNum,
            label: item.versionNum,
            ...item,
          }));
          const filterOption = (input: string, option: any) => {
            return option.value.toUpperCase().includes(input.toUpperCase());
          };
          return {
            allowClear: true,
            options,
            filterOption,
            placeholder: '请选择版本号',

            onChange: (value: any, option: any) => {
              values.versionId = option.id;
              values.updateSupport = values.versionId ? 2 : 3;
            },
          };
        },
      },
      rules: 'required',
      help: '如果是更新版本，需要输入新的版本号',
    },
    {
      fieldName: 'file',
      label: '样本数据',
      component: 'Upload',
      rules: 'required',
      help: '仅允许导入 xls、xlsx 格式文件',
    },
    {
      fieldName: 'updateSupport',
      label: '更新规则',
      component: 'RadioGroup',
      defaultValue: 1,
      rules: 'required',
      componentProps: {
        options: [
          {
            label: '覆盖当前版本',
            value: 1,
          },
          {
            label: '当前版本添加新数据',
            value: 2,
          },
          {
            label: '新增版本',
            value: 3,
          },
        ],
        buttonStyle: 'solid',
        optionType: 'button',
      },
      help: '是否新增版本，若不新增版本，则会在当前版本基础上进行更新',
    },
    {
      fieldName: 'splitType',
      label: '划分类型',
      component: 'Select',
      defaultValue: 'train',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.AI_DATASET_SPLIT_TYPE),
        placeholder:
          '请选择划分类型:train-训练 eval-评估 test-测试 predict-预测',
      },
    },
    {
      fieldName: 'source',
      label: '数据来源',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.AI_DATASET_SOURCE),
        placeholder: '请选择数据来源，如：manual/auto/imported',
      },
      dependencies: {
        triggerFields: ['updateSupport'],
        show: (values) => values.updateSupport === 3,
      },
    },
    {
      fieldName: 'language',
      label: '语言',
      component: 'Select',
      defaultValue: 'zh_CN',
      componentProps: {
        options: getDictOptions(DICT_TYPE.AI_LANGUAGE),
        placeholder: '请选择语言',
      },
      dependencies: {
        triggerFields: ['updateSupport'],
        show: (values) => values.updateSupport === 3,
      },
    },
    {
      fieldName: 'taskType',
      label: '阶段类型',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.AI_DATASET_TASK_TYPE),
        placeholder: '请选择阶段类型',
      },
      dependencies: {
        triggerFields: ['updateSupport'],
        show: (values) => values.updateSupport === 3,
      },
    },
    {
      fieldName: 'jsonTemplate',
      label: '训练模版',
      component: 'Textarea',
      componentProps: {
        rows: 4,
        placeholder: '请输入训练文件生成JSON模版',
      },
      dependencies: {
        triggerFields: ['updateSupport'],
        if: (values) => values.updateSupport === 3,
      },
    },
    {
      fieldName: 'description',
      label: '数据集介绍',
      component: 'RichTextarea',
      dependencies: {
        triggerFields: ['updateSupport'],
        if: (values) => values.updateSupport === 3,
      },
    },
    {
      fieldName: 'changeLog',
      label: '变更说明',
      component: 'Textarea',
      componentProps: {
        rows: 4,
        placeholder: '请输入变更说明',
      },
      dependencies: {
        triggerFields: ['updateSupport'],
        show: (values) => values.updateSupport === 3,
      },
    },
  ];
}
export function useCreateVersionFastSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      label: '数据集Id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'versionNum',
      label: '新版本号',
      component: 'Input',
      rules: 'required',
      help: '输入新的版本号',
    },
    {
      fieldName: 'auditStatus',
      label: '数据审核状态',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.INFRA_AUDIT_STATUS),
        placeholder: '请选择数据审核状态',
      },
    },
  ];
}
// 切换版本
export function useSwitchVersionSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      label: '数据集Id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'versionId',
      label: '版本号',
      component: 'Select',
      dependencies: {
        if: (values) => values.id,
        triggerFields: ['id'],
        async componentProps(values) {
          const list = await getVersionNumList(values.id);
          const options = list.map((item) => ({
            value: item.id,
            label: item.versionNum,
            ...item,
          }));
          return {
            allowClear: true,
            options,
            placeholder: '请选择版本号',
          };
        },
      },
      rules: 'required',
    },
    {
      fieldName: 'status',
      label: '数据集状态',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.AI_DATASET_STATUS),
        placeholder: '请选择数据集状态',
      },
    },
  ];
}
// 生成训练的json文件
export function useGenerateJsonFileSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      label: '数据集Id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'versionId',
      label: '版本号',
      component: 'Select',
      dependencies: {
        if: (values) => values.id,
        triggerFields: ['id'],
        async componentProps(values) {
          const list = await getVersionNumList(values.id);
          const options = list.map((item) => ({
            value: item.id,
            label: item.versionNum,
            ...item,
          }));
          return {
            allowClear: true,
            options,
            placeholder: '请选择版本号',
          };
        },
      },
      rules: 'required',
    },
    {
      fieldName: 'splitType',
      label: '划分类型',
      component: 'Select',
      defaultValue: 'train',
      rules: 'required',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.AI_DATASET_SPLIT_TYPE),
        placeholder: '请选择划分类型:训练 评估 测试 预测',
      },
    },
    {
      fieldName: 'downloadFlag',
      label: '是否同时下载',
      component: 'RadioGroup',
      defaultValue: false,
      rules: 'required',
      componentProps: {
        options: [
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ],
        buttonStyle: 'solid',
        optionType: 'button',
      },
    },
  ];
}
